<template>
  <div class="wrapper">
    <!-- 音视频 -->
    <!--
        本地视频流
        muted:
            本地视频流的video必须置为静音（muted)，否则会出现啸叫/回声等问题
            Mac / iPhone / iPad 需要用js设置muted属性
        autoplay：必须为激活状态
        playsinline：保证在ios safari中不全屏播放
     -->
    <video id="localVideo" class="video-model" muted autoplay playsinline></video>
    <!-- 远端视频流 -->
    <!-- <video id="remoteVideo" class="video-model" autoplay playsinline></video> -->
    
    <Button type="primary" @click.native="start('camera')">开始视频</Button>
    <Button type="primary" @click.native="end()">结束视频</Button>
    <Button type="primary" @click.native="getScreen()">切换屏幕共享</Button>
    <Button type="primary" @click.native="getCamera()">切换视频</Button>
  </div>
</template>
<script>

export default {
  data(){
    return {
      FetchSigCgi: 'https://www.qcloudtrtc.com/sxb_dev/?svc=account&cmd=authPrivMap',
      sdkappid: '',
      accountType: 14418, // accounttype 还是在文档中会找到
      userSig: '',
      streams: {
        screen:null,
        camera:null
      },
      screenSources: [],
      audioDevices: [],
      Bom: {
          /**
           * @description 读取location.search
           *
           * @param {String} n 名称
           * @return {String} search值
           * @example
           * 		$.bom.query('mod');
           */
          query: function (n) {
              var m = window.location.search.match(new RegExp("(\\?|&)" + n + "=([^&]*)(&|$)"));
              return !m ? "" : decodeURIComponent(m[2]);
          },
          getHash: function (n) {
              var m = window.location.hash.match(new RegExp("(#|&)" + n + "=([^&]*)(&|$)"));
              return !m ? "" : decodeURIComponent(m[2]);
          }
      }
    }
  },
  methods:{
    onKickout() {
        console.log("on kick out!");
    },
    onRelayTimeout(msg) {
        console.log("onRelayTimeout!" + (msg ? JSON.stringify(msg) : ""));
    },
    createVideoElement(id, isLocal) {
        var videoDiv = document.createElement("div");
        videoDiv.innerHTML = '<video id="' + id + '" autoplay ' + (isLocal ? 'muted' : '') + ' playsinline ></video>';
        document.querySelector("#remote-video-wrap").appendChild(videoDiv);

        return document.getElementById(id);
    },
    onLocalStreamAdd(info) {
        if (info.stream && info.stream.active === true) {
          var id = "localVideo";
          var video = document.getElementById(id);
          if (!video) {
            this.createVideoElement(id, true);
          }
          var video = document.getElementById(id)
          video.srcObject = info.stream;
          video.muted = true
          video.autoplay = true
          video.playsinline = true

        }
    },
    onRemoteStreamUpdate(info) {
        console.debug(info)
        if (info.stream && info.stream.active === true) {
            var id = "remoteVideo";
            var video = document.getElementById(id);
            if (!video) {
                video = this.createVideoElement(id);
            }
            video.srcObject = info.stream;
        } else {
            console.log('欢迎用户' + info.userId + '加入房间');
        }
    },
    onRemoteStreamRemove(info) {
        console.log(info.userId + ' 断开了连接');
        var videoNode = document.getElementById(info.videoId);
        if (videoNode) {
            videoNode.srcObject = null;
            document.getElementById(info.videoId).parentElement.removeChild(videoNode);
        }
    },
    switchAudioDevice(){
        // 采取随机的方式设置麦克风
        var index2 = Math.floor(Math.random() * this.audioDevices.length);
        RTC.chooseAudioDevice( this.audioDevices[index2] );
    },
    initRTC(opts) {
        var _this = this;
        var checkList = ['screen', 'window', 'tab', 'audio']
        checkList.forEach(function (item) {
            if ($("#" + item).prop("checked"))
            _this.screenSources.push(item);
        })
        //初始化
        window.RTC = new WebRTCAPI({
            userId: opts.userId,
            userSig: opts.userSig,
            sdkAppId: opts.sdkappid,
            accountType: opts.accountType
        });

        // 远端流新增/更新
        RTC.on("onRemoteStreamUpdate", this.onRemoteStreamUpdate)
        // 本地流新增
        RTC.on("onLocalStreamAdd", this.onLocalStreamAdd)
        // 远端流断开
        RTC.on("onRemoteStreamRemove", this.onRemoteStreamRemove)
        // 重复登录被T
        RTC.on("onKickout", this.onKickout)
        // 服务器超时
        RTC.on("onRelayTimeout", this.onRelayTimeout)
        // just for debugging
        //监听SDK错误
        RTC.on("onErrorNotify", function (info) {
            console.error(info)
        });
        RTC.on("onStreamNotify", function (info) {
            console.error('onStreamNotify', info)
        });
    },
    getMediaStream( type ,callback ){
      var _this = this; 
        if( _this.streams && _this.streams[type] ){
            callback( _this.streams[type] )
        }else if( type === 'screen' ){
            /* 
            | 参数                   | 类型       | 是否必须       | 描述            |
            | -------------------- | -------- | ------------- |
            | opts         | Object | 否 | 可以传空对象 {}    |
            | succ         | function |是 |  成功回调      |
            | fail         | function |否 |  失败回调      |

            #### opts 的参数定义

            | 参数                   | 类型       | 是否必须       | 描述            |
            | -------------------- | -------- | ------------- |
            | screen         | Boolean |否 | 是否采集屏幕分享 ,默认false   |
            | screenSources | string   |否 | 屏幕分享采集的媒介 用半角逗号隔开， 可选选项包括  screen window tab audio | 具体表现请参考下图 |
            | attributes         | Object |否 | 是否采集屏幕分享 ,默认false   |
            | videoDevice         | Device |否 | 指定设备，getVideoDevices 获取的device item   |
            | audioDevice         | Device |否 | 指定设备，getVideoDevices 获取的audio item   |

            #### attributes 的参数定义
            | width         | Boolean |否 | 分辨率宽度  |
            | height         | Boolean |否 | 分辨率高度 |
            | frameRate         | Boolean |否 | 帧率   |

            */
            RTC.getLocalStream({
                screen: true,
                screenSources: _this.screenSources.join(","),
                attributes:{
                    width:320,
                    height:320,
                    frameRate:10
                }
            },function(info){
                _this.streams['screen'] = info.stream
                console.debug('getLocalStream succ', info.stream)
                callback( info.stream )
            },function(error){
                console.error('failed', error)
            });
        }else if( type === 'camera' ){
            RTC.getLocalStream({
                attributes:{
                    width:640,
                    height:320,
                    frameRate:20
                }
            },function(info){
                console.error('camera')
                console.debug('getLocalStream succ', info.stream)
                _this.streams['camera'] = info.stream
                callback( info.stream )
            },function(error){
                console.error('failed', error)
            });
        }     
    },
    getScreen() {
      var _this = this;
      this.getMediaStream('screen', function(){
        _this.startRTC('screen');
      })
    },
    getCamera() {
      var _this = this;
      this.getMediaStream('camera', function(){
        _this.startRTC('camera');
      })
    },
    // 结束视频
    end () {
      RTC.quit(  function(){
        //退出成功
        console.log("退出成功");
    } , function(){
        //退出失败
        console.log("退出失败");
    });
    },
    // 开始视频，name：screen屏幕共享；camera视频    
    start( name ){
      var _this = this;
        this.login( function(){
            switch( name ){
                case 'audience':
                    _this.startRTC( 'audience' )
                    break;
                case 'screen':
                    _this.getScreen();
                    break;
                case 'camera':
                    _this.getCamera();
                    break;
            }
        });
    },
    startRTC( name ){
      var _this = this;
        if( !_this.streams[name] && name !=='audience' ) return;
        var stream = _this.streams[name];
        if( RTC.global.localStream ){
            console.debug( 'update ')
            //无需房间，更新流
            RTC.updateStream({
                role:name == 'screen' ?  "wp1280" : 'user',
                stream: _this.streams[name].clone()
            });
        }else{
            //进入房间，进行推流
            RTC.createRoom({
                roomid: _this.roomid * 1,
            }, function (info) {
                if( name ==='audience') {
                    return;
                }
                RTC.startRTC({
                    stream : stream.clone(),
                    role: name == 'screen' ?  "wp1280" : 'user'
                }, function (info) {
                    console.debug('推流成功');
                }, function (error) {
                    console.error('推流失败', error)
                });
            },function(error){
                console.error('进房失败', error)
            });
        }
    },
    detect() {
        WebRTCAPI.fn.detectRTC(function (data) {
            console.debug(data.screenshare);
            if (!data.screenshare) {
                alert("不支持")
            } else {
                alert('支持')
            }
        });
    },
    login( callback ) {
      console.log("login.......");
      var orderId = '13907';
      var uuid = "6bbeaaad252e4f73bba8d75a6bc093e7";
      var userId = '14984';
      var _this = this;

      this.getRequest('/WebRTC/getUserSig', {
        userId: userId,
        oid: orderId,
        otype: '4'
      }).then(resp=> {
          console.log("客户端通用接口：", resp);
          //一会儿进入房间要用到
          var userSig = resp.userSig;
          _this.sdkappid = resp.sdkappid;
          _this.roomid = resp.roomId;
          _this.privateMapKey = resp.privateMapKey;
          _this.accountType = resp.accountType;

          // 页面处理，显示视频流页面
          _this.initRTC({
            userId: userId,
            userSig: userSig,
            sdkappid: _this.sdkappid,
            accountType: _this.accountType,
            roomid: _this.roomid
          });
          
          if( callback ) {
            callback();
          }
      });

    }
  },
  created(){
    
  },

}
</script>
<style lang="less" scoped>
  .video-model {
    width: 100%;
    border: 2px solid #666;
    border-radius: 5px;
    background-image: url(/static/image/logo-hei.svg);
    background-position: center;
    background-size: 150px 100px;
    background-repeat: no-repeat;
    background-color: #fff;
  }
</style>